<template>
  <a-tabs default-active-key="doris">
    <a-tab-pane key="doris" :title="'Doris (' + dorisSelectList.length + ')'">
      <a-button type="primary" @click="onCreateSql('doris')" size="mini" style="margin: 5px">创建</a-button>
      <a-table :pagination="false" :columns="conlumns" :data="dorisSelectList">
        <template #select="{ record }">
          {{ record.selectsql ? '是' : '否' }}
        </template>
        <template #count="{ record }">
          {{ record.countsql ? '是' : '否' }}
        </template>
        <template #name="{ record }">
          <a-button type="text" @click="onOpenSql(record)">{{ record.name ? record.name : '匿名查询功能' }}</a-button>
        </template>
      </a-table>
    </a-tab-pane>
    <a-tab-pane key="selectdb" :title="'Selectdb (' + selectdbList.length + ')'">
      <a-button type="primary" @click="onCreateSql('selectdb')" size="mini" style="margin: 5px">创建</a-button>
      <a-table :pagination="false" :columns="conlumns" :data="selectdbList">
        <template #select="{ record }">
          {{ record.selectsql ? '是' : '否' }}
        </template>
        <template #count="{ record }">
          {{ record.countsql ? '是' : '否' }}
        </template>
        <template #name="{ record }">
          <a-button type="text" @click="onOpenSql(record)">{{ record.name ? record.name : '匿名查询功能' }}</a-button>
        </template>
      </a-table>
    </a-tab-pane>
    <a-tab-pane key="saas" :title="'SAAS (' + saasSelectList.length + ')'">
      <a-button type="primary" @click="onCreateSql('saas')" size="mini" style="margin: 5px">创建</a-button>
      <a-table :pagination="false" :columns="conlumns" :data="saasSelectList">
        <template #select="{ record }">
          {{ record.selectsql ? '是' : '否' }}
        </template>
        <template #count="{ record }">
          {{ record.countsql ? '是' : '否' }}
        </template>
        <template #name="{ record }">
          <a-button type="text" @click="onOpenSql(record)">{{ record.name ? record.name : '匿名查询功能' }}</a-button>
        </template>
      </a-table>
    </a-tab-pane>
    <a-tab-pane key="erp" :title="'ERP (' + erpSelectList.length + ')'">
      <a-button type="primary" @click="onCreateSql('erp')" size="mini" style="margin: 5px">创建</a-button>
      <a-table :pagination="false" :columns="conlumns" :data="erpSelectList">
        <template #select="{ record }">
          {{ record.selectsql ? '是' : '否' }}
        </template>
        <template #count="{ record }">
          {{ record.countsql ? '是' : '否' }}
        </template>
        <template #name="{ record }">
          <a-button type="text" @click="onOpenSql(record)">{{ record.name ? record.name : '匿名查询功能' }}</a-button>
        </template>
      </a-table>
    </a-tab-pane>
    <a-tab-pane key="hrwrite" :title="'人事系统写入接口 (' + hrwriteList.length + ')'">
      <a-button type="primary" @click="onCreateSql('hrwrite')" size="mini" style="margin: 5px">创建</a-button>
      <a-table :pagination="false" :columns="hrconlumns" :data="hrwriteList">
        <template #insert="{ record }">
          {{ record.insertsql ? '是' : '' }}
        </template>
        <template #update="{ record }">
          {{ record.updatesql ? '是' : '' }}
        </template>
        <template #delete="{ record }">
          {{ record.deletesql ? '是' : '' }}
        </template>
        <template #name="{ record }">
          <a-button type="text" @click="onOpenSql(record)">{{ record.name ? record.name : '匿名查询功能' }}</a-button>
        </template>
      </a-table>
    </a-tab-pane>
  </a-tabs>

  <a-modal v-model:visible="createSqlForm.visible" width="70%" top="50" :align-center="false">
    <template #title> 创建查询接口 </template>
    <div style="text-align: right; margin-bottom: 10px">
      <a-button v-show="dialogupdate.modified == false" @click="dialogupdate.modified = true">修改</a-button>
      <a-button v-show="dialogupdate.modified == true" @click="dialogupdate.modified = false" style="margin-right: 10px">取消</a-button>
      <a-button v-show="dialogupdate.modified == true" type="primary" status="success" @click="onSaveSelectSql">保存</a-button>
    </div>
    <a-form :model="dialogupdate" :style="{ width: '100%' }">
      <a-form-item field="name" tooltip="说明" label="名称" label-col-flex="100px">
        <a-input v-model="createSqlForm.name" max-length="30" placeholder="查询功能名字，比如:查询单品利润数据" />
      </a-form-item>
      <a-form-item field="name" tooltip="功能" label="系统" label-col-flex="100px">
        <a-input v-model="createSqlForm.sys" max-length="30" placeholder="某某系统,比如: sys, [a-zA-Z0-9]{3,30}" />
      </a-form-item>
      <a-form-item field="name" tooltip="功能" label="模块" label-col-flex="100px">
        <a-input v-model="createSqlForm.module" max-length="30" placeholder="某某模块,比如: sys, [a-zA-Z0-9]{3,30}" />
      </a-form-item>
      <a-form-item field="name" tooltip="功能" label="功能" label-col-flex="100px">
        <a-input v-model="createSqlForm.funName" placeholder="某某功能,比如: FindAsinProfit, [a-zA-Z0-9]{3,30}" />
      </a-form-item>

      <a-form-item field="name" v-show="createSqlForm.db === 'hrwrite'" label="类型" label-col-flex="100px">
        <a-select style="width: 180px" v-model="createSqlForm.sqltype">
          <a-option value="insert" label="insert" />
          <a-option value="update" label="update" />
          <a-option value="delete" label="delete" />
        </a-select>
      </a-form-item>

      <a-form-item field="name" tooltip="功能" label="编号" label-col-flex="100px">
        <div>
          <div>生成的ID不能改变，直观达意，清淅，和业务相关更好，例：product.companyProduct.FindProduct , 公司产品库查找产品功能</div>
          <div style="color: blue">{{ createSqlForm.sys }}.{{ createSqlForm.module }}.{{ createSqlForm.funName }}</div>
        </div>
      </a-form-item>
      <a-form-item label-col-flex="100px">
        <a-button type="primary" status="success" @click="onCreateSqlNext()">下一步</a-button>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button type="text" @click="createSqlForm.visible = false">关闭</a-button>
    </template>
  </a-modal>

  <a-modal v-model:visible="dialogupdate.visible" width="70%" top="50" :align-center="false">
    <template #title> SQL语句 【{{ dialogupdate.id }}】 </template>

    <a-tabs default-active-key="base">
      <a-tab-pane key="base" title="SQL语句">
        <div style="text-align: right; margin-bottom: 10px">
          <a-button v-show="dialogupdate.modified == false" @click="dialogupdate.modified = true">修改</a-button>
          <a-button v-show="dialogupdate.modified == true" @click="dialogupdate.modified = false" style="margin-right: 10px">取消</a-button>
          <a-button v-show="dialogupdate.modified == true" type="primary" status="success" @click="onSaveSelectSql">保存</a-button>
        </div>
        <a-form :model="dialogupdate" :style="{ width: '100%' }">
          <a-form-item field="post" label="数据库" label-col-flex="100px">
            {{ dialogupdate.db }}
          </a-form-item>
          <a-form-item v-if="dialogupdate.sqltype" field="post" label="SQL类型" label-col-flex="100px">
            {{ dialogupdate.sqltype }}
          </a-form-item>

          <a-form-item field="name" tooltip="说明" label="名称" label-col-flex="100px">
            <a-input v-if="dialogupdate.modified" v-model="dialogupdate.name" placeholder="please enter your username..." />
            <div v-else>{{ dialogupdate.name }}</div>
          </a-form-item>
          <a-form-item field="post" label="系统参数" label-col-flex="100px"> {SYS_USER_ID} {SYS_LIMIT} {SYS_OFFSET}, 更多参照《系统参数说明》 </a-form-item>

          <a-form-item v-if="dialogupdate.db === 'hrwrite' && dialogupdate.sqltype === 'insert'" field="post" label="Insert" label-col-flex="100px">
            <a-textarea v-if="dialogupdate.modified" v-model="dialogupdate.insertSql" placeholder="insert into" :auto-size="true" />
            <a-textarea v-else disabled v-model="dialogupdate.insertSql" placeholder="" style="height: 100px" />
          </a-form-item>

          <a-form-item v-if="dialogupdate.db === 'hrwrite' && dialogupdate.sqltype === 'delete'" field="post" label="Insert" label-col-flex="100px">
            <a-textarea v-if="dialogupdate.modified" v-model="dialogupdate.deleteSql" placeholder="delete" :auto-size="true" />
            <a-textarea v-else disabled v-model="dialogupdate.deleteSql" placeholder="" style="height: 100px" />
          </a-form-item>

          <a-form-item v-if="dialogupdate.db === 'hrwrite' && dialogupdate.sqltype === 'update'" field="post" label="Insert" label-col-flex="100px">
            <a-textarea v-if="dialogupdate.modified" v-model="dialogupdate.updateSql" placeholder="update" :auto-size="true" />
            <a-textarea v-else disabled v-model="dialogupdate.updateSql" placeholder="" style="height: 100px" />
          </a-form-item>

          <a-form-item v-if="dialogupdate.db === 'hrwrite'" field="post" label="ERP端接口" label-col-flex="100px">
            <div>
              <div>
                POST <span class="api">https://erpapi.selleroa.com/v1/bigdata/hr/write/data/</span><span class="api-id">{{ dialogupdate.id }}</span
                ><span style="color: red">.htm</span>
              </div>
            </div>
          </a-form-item>

          <a-form-item field="post" label-col-flex="100px">
            <div>
              <a-alert :show-icon="true"> 当SQL语句比较复杂的时候，可以写一些注释以便增加可读性。行注释方法： 以 "//" 开头的行会被认为是注释行<br /> </a-alert>
            </div>
          </a-form-item>

          <a-form-item v-if="dialogupdate.db != 'hrwrite'" field="post" label="Select 查数据" label-col-flex="100px">
            <a-textarea v-if="dialogupdate.modified" v-model="dialogupdate.selectSql" placeholder="Select * from xxx, 只允许写查询语句，语法参考mybaties sqlmap" :auto-size="true" />
            <a-textarea v-else disabled v-model="dialogupdate.selectSql" placeholder="Select * from xxx, 只允许写查询语句，语法参考mybaties sqlmap" :auto-size="true" style="min-height: 100px" />
          </a-form-item>
          <a-form-item v-if="dialogupdate.db != 'hrwrite'" field="post" label="Select Count" label-col-flex="100px">
            <a-textarea v-if="dialogupdate.modified" v-model="dialogupdate.countSql" placeholder="Select count(1) from xxx, 用于反回总行数，分页场景使用，可不填" :auto-size="true" />
            <a-textarea v-else disabled v-model="dialogupdate.countSql" placeholder="Select count(1) from xxx, 用于反回总行数，分页场景使用，可不填" :auto-size="true" />
          </a-form-item>
          <a-form-item field="post" label="导出参数" label-col-flex="100px" v-if="dialogupdate.db != 'hrwrite'">
            <a-textarea v-model="dialogupdate.testexportparam" />
          </a-form-item>
          <a-form-item field="post" label-col-flex="100px" v-if="dialogupdate.db != 'hrwrite'">
            <a-alert> 导出参数说明: targetCompanyId (公司ID), targetUserId(用户ID), fileModel(0:通用类型), sheetName(导出的Excel名称),columnList(字段列表{name:"字段中文名",key:"取值列，对应sql返回值",keyType:"1"}) </a-alert>
          </a-form-item>
          <a-form-item field="post" label="查询参数" label-col-flex="100px" v-if="dialogupdate.db != 'hrwrite'">
            <a-textarea v-model="dialogupdate.testparam" />
          </a-form-item>
          <a-form-item v-if="dialogupdate.db != 'hrwrite'" field="post" label="SAAS查询" label-col-flex="100px">
            POST <span class="api">https://api.saas.selleroa.com/finance/v1/bigdata/select/data/</span><span class="api-id">{{ dialogupdate.id }}</span>
          </a-form-item>
          <a-form-item v-if="dialogupdate.db != 'hrwrite'" field="post" label="SAAS导出" label-col-flex="100px">
            POST <span class="api">https://api.saas.selleroa.com/finance/v1/bigdata/select/export/</span><span class="api-id">{{ dialogupdate.id }}</span>
          </a-form-item>
          <a-form-item v-if="dialogupdate.db != 'hrwrite'" field="post" label-col-flex="100px"> <span>BODY</span> <span style="margin-left: 10px">{"pageSize":1,"currentPage":20,"needCount":true|false,param:{}}</span> </a-form-item>

          <a-form-item v-if="dialogupdate.db != 'hrwrite'" field="post" label="ERP查询" label-col-flex="100px">
            <div>
              <div>
                POST <span class="api">https://erpapi.selleroa.com/v1/bigdata/select/data/</span><span class="api-id">{{ dialogupdate.id }}</span
                ><span style="color: red">.htm</span>
              </div>
            </div>
          </a-form-item>
          <a-form-item v-if="dialogupdate.db != 'hrwrite'" field="post" label="ERP导出" label-col-flex="100px">
            <div>
              <div>
                POST <span class="api">https://erpapi.selleroa.com/v1/bigdata/select/export/</span><span class="api-id">{{ dialogupdate.id }}</span
                ><span style="color: red">.htm</span>
              </div>
            </div>
          </a-form-item>

          <a-form-item v-if="dialogupdate.db != 'hrwrite'" field="post" label-col-flex="100px">
            <div>
              <div> <span style="margin-left: 10px">BODY</span> <span style="margin-left: 10px">{"pageSize":1,"currentPage":20,"needCount":true|false,param:{}}</span> </div>
              <div style="color: red">注意，ERP的接口比SAAS多一个后缀</div>
            </div>
          </a-form-item>

          <a-form-item label-col-flex="100px" v-if="dialogupdate.db != 'hrwrite'">
            <a-button html-type="submit" @click="onTestFind(false)">测试运行 Select</a-button>
            <a-button html-type="submit" @click="onTestFind(true)" style="margin-left: 10px">测试运行 Select & Count</a-button>
            <a-button html-type="submit" @click="onExportFind()" style="margin-left: 10px">导出</a-button>
          </a-form-item>
          <a-form-item v-show="dialogupdate.rs" field="post" label="结果" label-col-flex="100px">
            <div class="result">
              <div>{{ dialogupdate.rs }}</div>
            </div>
          </a-form-item>
          <a-form-item v-show="dialogupdate.rs" field="post" label-col-flex="100px">
            <a-button @click="onCopyResult">Copy Result</a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>

      <a-tab-pane key="sys_param" title="系统参数说明">
        <div style="color: red">注意：只有分页参数用 ${}来绑定，其它的都应该用 #{}来绑定</div>
        <a-table :columns="conlumns_param" :data="sysParamList" :pagination="false" />
      </a-tab-pane>
    </a-tabs>

    <template #footer>
      <a-button type="text" @click="dialogupdate.visible = false">关闭</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import { onMounted, ref } from 'vue'
  import { listSelectSql, executeSelectSql, saveSelectSql, createSelectSql, executeExportSql } from '@/api/task'
  import { Message } from '@arco-design/web-vue'
  import useClipboard from 'vue-clipboard3'
  let dorisSelectList = ref([])
  let selectdbList = ref([])
  let saasSelectList = ref([])
  let erpSelectList = ref([])
  let createSqlForm = ref({ visible: false, sys: '', module: '', funName: '', name: '', db: '', sqltype: '' })
  let dialogupdate = ref({
    visible: false,
    id: '',
    name: '',
    selectSql: '',
    countSql: '',
    testparam: '{"pageSize":1,"currentPage":20,"needCount":false,"param":{"column1":"value1"}}',
    testexportparam: '{"pageSize":1,"currentPage":20,"needCount":false,"targetCompanyId":"yfn","targetUserId":"xxx","fileModel":0,"sheetName":"ExcelName","columnList":[{"name":"字段名","key":"column1","keyType":"1"}],"param":{}}',
    rs: '',
    modified: false,
    db: '',
    sqltype: '',
    insertSql: '',
    updateSql: '',
    deleteSql: '',
  })
  let hrwriteList = ref([])
  let sqltypes = ref(['insert', 'update', 'delete'])
  let conlumns = [
    {
      title: '编号',
      dataIndex: 'id',
    },
    {
      title: '数据库',
      dataIndex: 'db',
    },
    {
      title: '名称',
      dataIndex: 'name',
      slotName: 'name',
    },
    {
      title: 'select',
      slotName: 'select',
    },
    {
      title: 'count',
      slotName: 'count',
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
    },
    {
      title: '修改时间',
      dataIndex: 'gmtWrite',
    },
  ]
  let hrconlumns = [
    {
      title: '编号',
      dataIndex: 'id',
    },
    {
      title: '数据库',
      dataIndex: 'db',
    },
    {
      title: '名称',
      dataIndex: 'name',
      slotName: 'name',
    },
    {
      title: 'sqltype',
      dataIndex: 'sqltype',
    },
    {
      title: 'Insert',
      slotName: 'insert',
    },
    {
      title: 'Update',
      slotName: 'update',
    },
    {
      title: 'Delete',
      slotName: 'delete',
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
    },
    {
      title: '修改时间',
      dataIndex: 'gmtWrite',
    },
  ]
  let conlumns_param = [
    {
      title: '变量',
      dataIndex: 'name',
    },
    {
      title: '说明',
      dataIndex: 'remarks',
    },
  ]
  let sysParamList = ref([
    {
      name: '{SYS_USER_ID}',
      remarks: '当前登录ID',
    },
    {
      name: '{SYS_COMPANY_ID}',
      remarks: '当前登录公司ID',
    },
    {
      name: '{SYS_DEPT_ID}',
      remarks: '当前登录部门ID',
    },
    {
      name: '{SYS_LIMIT}',
      remarks: '分页用的Limit值, eg:  limit ${SYS_LIMIT}',
    },
    {
      name: '{SYS_OFFSET}',
      remarks: '分页用的offset值 eg:  offset ${SYS_OFFSET}',
    },
    {
      name: '{SYS_INVOKE_FROM}',
      remarks: '判定是从ERP调用，还是SAAS中调用  取值  SAAS | ERP  ',
    },
    {
      name: '{SYS_IS_ADMIN}',
      remarks: '是否管理员  null | true | false',
    },
    {
      name: '{SYS_DEPT_ID_LIST}',
      remarks: '部门及子部门ID列表 ["部门ID","部门ID",...] , 默认无值，要想有值，传入参数 needDeptList:true',
    },
    {
      name: '{SYS_SELLER_ID_LIST}',
      remarks: '拥有的亚马逊SellerId List ["SellerId","SellerId",...] , 默认无值，要想有值，传入参数 needShopList:true',
    },
    {
      name: '{SYS_FUNC_CODE}',
      remarks: '权限代码   默认无值，要想有值，传入参数 SYS_FUNC:具体的权限代码',
    },
    {
      name: '{SYS_FUNC_LEVEL}',
      remarks: '权限级别(数值) ,0 : 自己 ,1: 自己及本部门,2 ：自已、本部门及子部门,3： 公司权限 , 默认无值，要想有值，传入参数 SYS_FUNC:具体的权限代码',
    },
  ])
  onMounted(async () => {
    await loadsql()
  })

  const loadsql = async () => {
    let result = await listSelectSql({ db: 'doris' })
    dorisSelectList.value = result?.data?.list || []
    result = await listSelectSql({ db: 'selectdb' })
    selectdbList.value = result?.data?.list || []
    result = await listSelectSql({ db: 'saas' })
    saasSelectList.value = result?.data?.list || []
    result = await listSelectSql({ db: 'erp' })
    erpSelectList.value = result?.data?.list || []
    result = await listSelectSql({ db: 'hrwrite' })
    hrwriteList.value = result?.data?.list || []
  }

  const onOpenSql = (sql: any) => {
    //alert(JSON.stringify(sql))
    dialogupdate.value.visible = true
    dialogupdate.value.id = sql.id
    dialogupdate.value.name = sql.name ? sql.name : '匿名查询功能'
    dialogupdate.value.selectSql = sql.selectsql
    dialogupdate.value.countSql = sql.countsql
    dialogupdate.value.testparam = sql.testparam
    dialogupdate.value.db = sql.db
    dialogupdate.value.sqltype = sql.sqltype
    dialogupdate.value.insertSql = sql.insertsql
    dialogupdate.value.updateSql = sql.updatesql
    dialogupdate.value.deleteSql = sql.deletesql
  }
  const onExportFind = async () => {
    let p = JSON.parse(dialogupdate.value.testexportparam || '{}')
    //alert(JSON.stringify(p))
    let lastparam = Object.assign({}, p)
    let rs = await executeExportSql(dialogupdate.value.id, lastparam)
    Message.success('请一会到下载中心查看结果')
  }
  const onTestFind = async (needCount: boolean) => {
    dialogupdate.value.rs = 'Loading'
    let p = JSON.parse(dialogupdate.value.testparam || '{}')
    //alert(JSON.stringify(p))
    let lastparam = Object.assign({ needCount: needCount }, p)
    let rs = await executeSelectSql(dialogupdate.value.id, lastparam)
    dialogupdate.value.rs = JSON.stringify(rs)
  }

  const onSaveSelectSql = async () => {
    let p = JSON.parse(dialogupdate.value.testparam || '{}')
    let rs = await saveSelectSql({ name: dialogupdate.value.name, id: dialogupdate.value.id, selectsql: dialogupdate.value.selectSql, insertsql: dialogupdate.value.insertSql, updatesql: dialogupdate.value.updateSql, deletesql: dialogupdate.value.deleteSql, countsql: dialogupdate.value.countSql, testparam: JSON.stringify(p) })
    Message.success('保存成功')
    dialogupdate.value.modified = false
    await loadsql()
  }
  const onCreateSql = async (db: any) => {
    createSqlForm.value.visible = true
    createSqlForm.value.db = db
    await loadsql()
  }

  const onCreateSqlNext = async () => {
    let param = { id: createSqlForm.value.sys + '.' + createSqlForm.value.module + '.' + createSqlForm.value.funName, name: createSqlForm.value.name, db: createSqlForm.value.db, sqltype: createSqlForm.value.sqltype }
    let rs = await createSelectSql(param)
    if (rs?.data?.id) {
      createSqlForm.value.visible = false
      onOpenSql(rs?.data)
      return
    }
    Message.error('好像出错了')
    alert(JSON.stringify(rs))
  }
  const { toClipboard } = useClipboard()
  const onCopyResult = async () => {
    toClipboard(dialogupdate.value.rs)
    Message.success('复制成功')
  }
</script>

<style lang="less" scoped>
  .api {
    color: green;
    margin-left: 10px;
  }
  .api-id {
    color: blue;
    font-weight: bold;
  }
  .sql-content {
    max-width: 600px;
    overflow: scroll;
  }
  .result {
    width: 100%;
    overflow: scroll;
    max-height: 200px;
  }
</style>
